// // ******************************************************************
// //       /\ /|       @file       LoggingHelper.cs
// //       \ V/        @brief      await29
// //       | "")       @author     Await, 285283010@qq.com
// //       /  |
// //      /  \\        @Modified   2025-03-01 11:03
// //    *(__\_\        @Copyright  Copyright (c) , 2025-03-01 11:03 Await
// // ******************************************************************

using Microsoft.Extensions.Logging;

namespace AutomaticSubtitles.Service.Infrastructure.Helper;

/// <summary>
/// 日志辅助类，提供静态帮助方法中使用的日志功能
/// </summary>
public static class LoggingHelper
{
    private static ILoggerFactory _loggerFactory;
    private static readonly object _lock = new object();
    private static bool _initialized;

    /// <summary>
    /// 初始化日志工厂
    /// </summary>
    /// <param name="loggerFactory">日志工厂实例</param>
    public static void Initialize(ILoggerFactory loggerFactory)
    {
        if (_initialized) return;

        lock (_lock)
        {
            if (_initialized) return;
            _loggerFactory = loggerFactory;
            _initialized = true;
        }
    }

    /// <summary>
    /// 获取指定类型的日志记录器
    /// </summary>
    /// <typeparam name="T">日志分类类型</typeparam>
    /// <returns>日志记录器</returns>
    public static ILogger GetLogger<T>()
    {
        EnsureInitialized();
        return _loggerFactory.CreateLogger<T>();
    }

    /// <summary>
    /// 获取指定类别名的日志记录器
    /// </summary>
    /// <param name="categoryName">日志分类名</param>
    /// <returns>日志记录器</returns>
    public static ILogger GetLogger(string categoryName)
    {
        EnsureInitialized();
        return _loggerFactory.CreateLogger(categoryName);
    }

    private static void EnsureInitialized()
    {
        if (!_initialized)
        {
            lock (_lock)
            {
                if (!_initialized)
                {
                    // 如果没有初始化，使用默认日志工厂
                    _loggerFactory = LoggerFactory.Create(builder =>
                    {
                        builder.AddConsole();
                    });
                    _initialized = true;
                }
            }
        }
    }
}